package cn.sumpu.app.guoguojie.util;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;

public class HttpProxy {

	/**
	 * 
	 * @param url
	 * @return nickname
	 * @throws Exception
	 */
	public static String doHttpGet(String url) throws Exception {
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);

		HttpResponse response = httpclient.execute(httpGet);
		HttpEntity resEntity = response.getEntity();

		String ret = null;
		if (resEntity != null) {
			String charset = EntityUtils.getContentCharSet(resEntity);
			if (null == charset) {
				charset = "UTF-8";
			}
			ret = EntityUtils.toString(resEntity, charset);

		}
		httpclient.getConnectionManager().shutdown();
		return ret;
	}

	/**
	 * 发送POST请求.
	 * 
	 * @param url
	 *            请求URL
	 * @param params
	 *            请求参数
	 * @return 请求结果
	 * @throws Exception
	 *             请求失败
	 */
	public static String doPost(String url, Map<String, String> params)
			throws Exception {
		HttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(
				CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		HttpPost httpPost = new HttpPost(url);
		MultipartEntity multipartEntity = new MultipartEntity();
		Set<String> keySet = params.keySet();
		for (String key : keySet) {
			multipartEntity.addPart(key, new StringBody(params.get(key),
					Charset.forName("UTF-8")));
		}
		httpPost.setEntity(multipartEntity);
		HttpResponse response = httpclient.execute(httpPost);
		HttpEntity resEntity = response.getEntity();
		String ret = null;
		if (resEntity != null) {
			String charset = EntityUtils.getContentCharSet(resEntity);
			if (null == charset) {
				charset = "UTF-8";
			}
			ret = EntityUtils.toString(resEntity, charset);
		}
		httpclient.getConnectionManager().shutdown();
		return ret;
	}

	/**
	 * 通过HTTP协议把图片数据发送到指定的图片服务器上
	 * 
	 * @param serverUrl
	 *            图片服务器地址
	 * @param savePath
	 *            图片在图片服务器上的保存地址
	 * @param saveFilename
	 *            图片在图片服务器上的保存文件名
	 * @param imageData
	 *            图片数据
	 * @return ok-成功；error-失败
	 * @throws Exception
	 *             HTTP交互过程中产生异常
	 */
	public static String sendImage(String serverUrl, String savePath,
			String saveFilename, byte[] imageData) throws Exception {
		HttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(
				CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		HttpPost httppost = new HttpPost(serverUrl/* processServerUrl(serverUrl) */);

		MultipartEntity multipartEntity = new MultipartEntity();
		multipartEntity.addPart("savePath",
				new StringBody(savePath, Charset.forName("UTF-8")));
		multipartEntity.addPart("saveFilename", new StringBody(saveFilename,
				Charset.forName("UTF-8")));
		multipartEntity.addPart("pic",
				new ByteArrayBody(imageData, "image.jpg"));
		httppost.setEntity(multipartEntity);

		HttpResponse response = httpclient.execute(httppost);
		HttpEntity resEntity = response.getEntity();

		String ret = null;
		if (resEntity != null) {
			String charset = EntityUtils.getContentCharSet(resEntity);
			ret = EntityUtils.toString(resEntity, charset);
		}

		httpclient.getConnectionManager().shutdown();

		return ret;
	}

	/**
	 * 通过HTTP协议删除指定的图片服务器上的图片文件
	 * 
	 * @param serverUrl
	 *            图片服务器地址
	 * @param imageFile
	 *            要删除的图片在图片服务器上的保存文件名
	 * @return ok-成功；error-失败
	 * @throws Exception
	 *             HTTP交互过程中产生异常
	 */
	public static String deleteImage(String serverUrl, String imageFile)
			throws Exception {
		HttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(
				CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		HttpPost httppost = new HttpPost(serverUrl/* processServerUrl(serverUrl) */);

		MultipartEntity multipartEntity = new MultipartEntity();
		multipartEntity.addPart("imageFile",
				new StringBody(imageFile, Charset.forName("UTF-8")));
		httppost.setEntity(multipartEntity);

		HttpResponse response = httpclient.execute(httppost);
		HttpEntity resEntity = response.getEntity();

		String ret = null;
		if (resEntity != null) {
			String charset = EntityUtils.getContentCharSet(resEntity);
			ret = EntityUtils.toString(resEntity, charset);
		}

		httpclient.getConnectionManager().shutdown();

		return ret;
	}

	// public static String processServerUrl(String serverUrl) {
	// if (serverUrl.indexOf(":8080") == -1) {
	// int index = serverUrl.lastIndexOf("/");
	// return serverUrl.substring(0, index) + ":8080"
	// + serverUrl.substring(index);
	// } else {
	// return serverUrl;
	// }
	//
	// }

	// just test
	public static void main(String[] args) throws Exception {
		/*
		 * String serverUrl = "http://192.168.0.105/receiveImage.htm"; String
		 * savePath = "pic/album/20110711/1324327428"; String saveFilename =
		 * "7d905506-6595-4949-b06a-cda0c1c57231.jpg"; String fileName =
		 * "C:\\Documents and Settings\\All Users.WINDOWS\\Documents\\My Pictures\\示例图片\\Sunset.jpg"
		 * ; InputStream fis = new FileInputStream(fileName); byte[] b = new
		 * byte[fis.available()]; fis.read(b);
		 * System.err.println(sendImage(serverUrl, savePath, saveFilename, b));
		 */

		// serverUrl = "http://192.168.0.105:8080/deleteImage.htm";
		// String imageFile =
		// "tmp/pic/20110627/1324327428/76c31059-82cc-4141-a932-97e1f390fe02.jpg";
		// System.err.println(deleteImage(serverUrl, imageFile));
		// String data =
		// doHttpGet("https://graph.qq.com/user/get_user_info?access_token=6C62B01B0EF4C9559DF9EC550608E2AC&oauth_consumer_key=100224191&openid=8DED079C3AB03D225710EBE4E67ADFB1&format=json");
		Map<String, String> params = new HashMap<String, String>();
		params.put("curcy", "100");
		params.put("curcyType", "01");
		params.put("summary", "attack");
		params.put("nickname", "Nick");
		String data = doPost(
				"http://192.168.0.107/misc/currency/giveCurcy.htm", params);
		System.out.println(data);
	}

}
